package com.briup.cms.config;

import com.briup.cms.web.interceptor.JwtInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * webmvc的配置类
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
	private static final Logger LOGGER = LoggerFactory.getLogger(WebConfig.class);

	@Autowired
	private ConfigProperties configProperties;


	// 跨域配置
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping(configProperties.getCorsMapping())
				.allowedOrigins(configProperties.getCorsAllowedOrigins())
				.allowedMethods(configProperties.getCorsAllowedMethods())
				.allowedHeaders(configProperties.getCorsAllowedHeaders())
				.allowCredentials(configProperties.getCorsAllowCredentials())
				.maxAge(configProperties.getCorsMaxAge());
//		registry.addMapping("/**")
//				.allowedOrigins("*")
//				.allowedMethods("GET","POST","PUT","OPTIONS","DELETE","PATCH")
//				.allowedHeaders("*")
//				.allowCredentials(false)
//				.maxAge(3600);
	}

	// 添加jwt拦截器,并指定拦截路径
	// 例如，/auth/**
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(jwtInterceptor())
				.addPathPatterns(configProperties.getAuthPath());
	}

	// jwt拦截器
	@Bean
	public JwtInterceptor jwtInterceptor() {
		return new JwtInterceptor();
	}


	/**
	 * 配置上传路径
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		String localUploadBastPath = configProperties.getLocalUploadBastPath();

		if(localUploadBastPath == null || "".equals(localUploadBastPath)){
			String filePath = WebConfig.class.getClassLoader().getResource("").getPath();
			if(filePath.indexOf(".jar")>0){
				filePath = filePath.substring(0, filePath.indexOf(".jar"));
			}else if(filePath.indexOf("classes")>0){
				filePath = "file:"+filePath.substring(0, filePath.indexOf("classes"));
			}
			filePath = filePath.substring(0, filePath.lastIndexOf("/"))+"/images/";
			localUploadBastPath = filePath;
		}
		LOGGER.info("文件本地上传路径为 : local-upload-bast-path = "+ localUploadBastPath);

		//注意如果是项目外部的资源需要加file:
		registry.addResourceHandler("/static/**/").addResourceLocations(localUploadBastPath);
		registry.addResourceHandler("/static/**/").addResourceLocations("file:"+localUploadBastPath);
	}


	// 添加全局接收日期参数时候的转换器
	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addConverter(new StringToDateConverter());
	}

	// 配置全局转换器
	// 例如，yyyy-MM-dd HH:mm:ss
	class StringToDateConverter implements Converter<String, Date> {

		@Override
		public Date convert(String source) {
			Date target = null;
			if(StringUtils.hasLength(source)) {
				// 保存一下当前参数，如果添加时分秒报错，那么可以不添加时分秒再试试
				String sourceBak = source;

				// 如果是传的时候 1999-11-11 则自动添加为 1999-11-11 00:00:00
				if(!source.contains(":")){
					source = source.trim()+" 00:00:00";
				}
				SimpleDateFormat format = new SimpleDateFormat(configProperties.getStringParamToDateFormat());
				try {
					target = format.parse(source);
				} catch (Exception e1) {
					try {
						target = format.parse(sourceBak);
					} catch (Exception e2) {
						throw new RuntimeException(String.format("parser %s to Date fail", sourceBak));
					}
				}
			}
			return target;
		}
	}

}
